include("../../static/js/config.js");
include("../../static/js/common.js");

$(function () {

    var form, editor;
    layui.use(['form'], function () {

        form = layui.form;
        editor = editormd("my-editormd", {
            height: 640,
            syncScrolling: "single",
            path: "../../static/editor.md/lib/",
            //这个配置在simple.html中并没有，但是为了能够提交表单，使用这个配置可以让构造出来的HTML代码直接在第二个隐藏的textarea域中，方便post提交表单。
            saveHTMLToTextarea: true,
            imageUpload: true,
            imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL : "/uploadImage",//注意你后端的上传图片服务地址
            onload: function(){
                this.width("100%");
                this.height(480);
            }
        });

        form.on('submit(update)', function(data){
            var id = $("#id").val();
            var title = $("#title").val();
            var musicId = $("#musicId").val();
            var html = editor.getHTML();
            var markdown = editor.getMarkdown();

            var description = $("#description").val();
            var state = $('#state option:selected').val()

            request("/admin/blog/update", {id:id, title:title, description:description, musicId:musicId, state:state, content:html, markdown:markdown}, function (data) {
                if (data.code == 200){
                    layer.msg("操作成功", {icon: 1});
                    setTimeout(function () {
                        if (window.parent){
                            window.parent.layer.closeAll();
                            window.parent.location.reload();
                        }
                    }, 3000);
                } else {
                    layer.msg(data.msg, {icon: 5});
                }
            });
            return false;
        });

        init();
    });

    function init() {
        request('/admin/blog/detail', {id: getParam('id')}, function(res){
            if (res.code == 200){
                $('#id').val(res.data.id);
                $('#title').val(res.data.title);
                $('#musicId').val(res.data.musicId);
                $('#createDate').val(res.data.createDate);
                $('#description').val(res.data.description);

                $('#state').val(res.data.state);
                $('textarea[name="content"]').val(res.data.markdown);
                layui.form.render() ;
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        });
    }
});